import 'package:flame/components.dart';
import 'package:freedom/page/mahjong/bloc/user_state.dart';
import 'package:freedom/page/mahjong/common/common_card.dart';
import 'package:freedom/page/mahjong/common/mahjong_context.dart';
import 'package:freedom/page/mahjong/event/start_game_event.dart';
import 'package:freedom/page/mahjong/event/user_select_card.dart';
import 'package:freedom/page/mahjong/util/user_location.dart';
import 'package:freedom/util/voice_message_sound.dart';

abstract class AbstractExport extends PositionComponent {
  late UserState currentUserState;
  AbstractExport({
    super.position,
    super.size,
    super.anchor,
  }) {
    currentUserState = MahjongContext.getUserState(userDirection())!;
    initEvent(currentUserState);
  }

  //真实牌的对象
  List<CommonCard> eportAllCard = [];

  int cardIndex = 999999;

  /// 初始化牌

  void reflashUI(List<int> cards);

  /// 最后一张牌

  Vector2 getLast();

  ///  最后一张牌落地的位置

  Vector2 getLastPoint();

  /// 获取出牌后 麻将产生的位移

  Vector2 getLastPointByScc(Vector2 currentCardPoint);

  /// 出牌事件
  /// 在麻将桌上面添加一张牌
  ///
  ///
  CommonCard exportCard(int card);

  void defaultExportCard(int card) {
    // 执行出牌动画
    exportCard(card);
    // 播放出牌声音 延迟播放出牌是什么万条筒
    /* VoiceMessageSound().play("EXPORT");
    Future.delayed(const Duration(milliseconds: 200), () {
      VoiceMessageSound().play("card$card");
    }); */
    VoiceMessageSound().play("card$card");
  }

  /// 移出最后一张牌
  /// 并且调整当前数组长度
  void removeLastCard() {
    if (eportAllCard.isNotEmpty) {
      eportAllCard.last.removeFromParent();
      eportAllCard = eportAllCard.sublist(0, eportAllCard.length - 1);
    }
  }

  Direction userDirection() {
    return Direction.BOTTOM;
  }

  void initEvent(UserState userStateParam) {
    // 游戏开始
    MahjongContext.registerUserFunc<StartGameEvent>(userStateParam.userId,
        (event) {
      eportAllCard = [];
      currentUserState.exportCards = "";
      reflashUI([]);
    });
    MahjongContext.registerRoomFunc<UserSelectCardEvent>((event) {
      for (var element in eportAllCard) {
        if (element.cardCode == event.cardCode) {
          element.focus = true;
        } else {
          element.focus = false;
        }
      }
    });
  }
}
